﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Newtonsoft.Json;

namespace DidaManager.Models
{
    /// <summary>
    /// HJ212系统类型数据模型
    /// </summary>
    public class SystemTypeItem
    {
        /// <summary>
        /// 系统类型名称
        /// </summary>
        [JsonProperty("name")]
        public string Name { get; set; } = string.Empty;
        
        /// <summary>
        /// 系统类型ID
        /// </summary>
        [JsonProperty("id")]
        public int Id { get; set; }
    }

    /// <summary>
    /// HJ212系统类型配置数据模型
    /// </summary>
    public class SystemTypeConfig
    {
        /// <summary>
        /// 系统类型列表
        /// </summary>
        [JsonProperty("types")]
        public List<SystemTypeItem> Types { get; set; } = new List<SystemTypeItem>();
    }

    /// <summary>
    /// HJ212系统类型管理器
    /// </summary>
    public class HJ212SystemType
    {
        /// <summary>
        /// 全局存储的系统类型数据
        /// </summary>
        private static SystemTypeConfig? _systemTypeConfig;
        
        /// <summary>
        /// 是否已加载数据
        /// </summary>
        private static bool _isDataLoaded = false;
        
        /// <summary>
        /// 配置文件路径
        /// </summary>
        private static string _configFilePath = string.Empty;

        /// <summary>
        /// 获取是否已加载数据
        /// </summary>
        public static bool IsDataLoaded => _isDataLoaded;

        /// <summary>
        /// 获取当前配置文件路径
        /// </summary>
        public static string ConfigFilePath => _configFilePath;

        /// <summary>
        /// 获取所有系统类型数据（只读）
        /// </summary>
        public static IReadOnlyList<SystemTypeItem> AllSystemTypes => 
            _systemTypeConfig?.Types?.AsReadOnly() ?? new List<SystemTypeItem>().AsReadOnly();

        /// <summary>
        /// 从JSON文件加载系统类型配置
        /// </summary>
        /// <param name="filePath">JSON文件路径</param>
        /// <returns>是否加载成功</returns>
        public static bool LoadFromJsonFile(string filePath)
        {
            try
            {
                // 检查文件是否存在
                if (!File.Exists(filePath))
                {
                    return false;
                }

                // 读取JSON文件内容
                string jsonContent = File.ReadAllText(filePath, new UTF8Encoding(false));
                
                // 反序列化JSON数据
                _systemTypeConfig = Newtonsoft.Json.JsonConvert.DeserializeObject<SystemTypeConfig>(jsonContent);
                
                if (_systemTypeConfig?.Types != null)
                {
                    _isDataLoaded = true;
                    _configFilePath = filePath;
                    return true;
                }
                
                return false;
            }
            catch
            {
                _isDataLoaded = false;
                _configFilePath = string.Empty;
                return false;
            }
        }

        /// <summary>
        /// 异步加载JSON文件
        /// </summary>
        /// <param name="filePath">JSON文件路径</param>
        /// <returns>加载任务</returns>
        public static async Task<bool> LoadFromJsonFileAsync(string filePath)
        {
            return await Task.Run(() => LoadFromJsonFile(filePath));
        }

        /// <summary>
        /// 获取所有系统类型名称列表
        /// </summary>
        /// <returns>系统类型名称列表</returns>
        public static List<string> GetAllSystemTypeNames()
        {
            if (!_isDataLoaded || _systemTypeConfig?.Types == null)
            {
                return new List<string>();
            }
            
            return _systemTypeConfig.Types.Select(t => t.Name).ToList();
        }

        /// <summary>
        /// 获取所有系统类型ID列表
        /// </summary>
        /// <returns>系统类型ID列表</returns>
        public static List<int> GetAllSystemTypeIds()
        {
            if (!_isDataLoaded || _systemTypeConfig?.Types == null)
            {
                return new List<int>();
            }
            
            return _systemTypeConfig.Types.Select(t => t.Id).ToList();
        }

        /// <summary>
        /// 根据ID获取系统类型名称
        /// </summary>
        /// <param name="id">系统类型ID</param>
        /// <returns>系统类型名称，如果不存在则返回空字符串</returns>
        public static string GetSystemTypeNameById(int id)
        {
            if (!_isDataLoaded || _systemTypeConfig?.Types == null)
            {
                return string.Empty;
            }
            
            var systemType = _systemTypeConfig.Types.FirstOrDefault(t => t.Id == id);
            return systemType?.Name ?? string.Empty;
        }

        /// <summary>
        /// 根据名称获取系统类型ID
        /// </summary>
        /// <param name="name">系统类型名称</param>
        /// <returns>系统类型ID，如果不存在则返回-1</returns>
        public static int GetSystemTypeIdByName(string name)
        {
            if (!_isDataLoaded || _systemTypeConfig?.Types == null)
            {
                return -1;
            }
            
            var systemType = _systemTypeConfig.Types.FirstOrDefault(t => 
                string.Equals(t.Name, name, StringComparison.OrdinalIgnoreCase));
            return systemType?.Id ?? -1;
        }

        /// <summary>
        /// 根据ID获取系统类型对象
        /// </summary>
        /// <param name="id">系统类型ID</param>
        /// <returns>系统类型对象，如果不存在则返回null</returns>
        public static SystemTypeItem? GetSystemTypeById(int id)
        {
            if (!_isDataLoaded || _systemTypeConfig?.Types == null)
            {
                return null;
            }
            
            return _systemTypeConfig.Types.FirstOrDefault(t => t.Id == id);
        }

        /// <summary>
        /// 根据名称获取系统类型对象
        /// </summary>
        /// <param name="name">系统类型名称</param>
        /// <returns>系统类型对象，如果不存在则返回null</returns>
        public static SystemTypeItem? GetSystemTypeByName(string name)
        {
            if (!_isDataLoaded || _systemTypeConfig?.Types == null)
            {
                return null;
            }
            
            return _systemTypeConfig.Types.FirstOrDefault(t => 
                string.Equals(t.Name, name, StringComparison.OrdinalIgnoreCase));
        }

        /// <summary>
        /// 检查系统类型ID是否存在
        /// </summary>
        /// <param name="id">系统类型ID</param>
        /// <returns>是否存在</returns>
        public static bool IsSystemTypeIdExists(int id)
        {
            if (!_isDataLoaded || _systemTypeConfig?.Types == null)
            {
                return false;
            }
            
            return _systemTypeConfig.Types.Any(t => t.Id == id);
        }

        /// <summary>
        /// 检查系统类型名称是否存在
        /// </summary>
        /// <param name="name">系统类型名称</param>
        /// <returns>是否存在</returns>
        public static bool IsSystemTypeNameExists(string name)
        {
            if (!_isDataLoaded || _systemTypeConfig?.Types == null)
            {
                return false;
            }
            
            return _systemTypeConfig.Types.Any(t => 
                string.Equals(t.Name, name, StringComparison.OrdinalIgnoreCase));
        }

        /// <summary>
        /// 清空数据
        /// </summary>
        public static void ClearData()
        {
            _systemTypeConfig = null;
            _isDataLoaded = false;
            _configFilePath = string.Empty;
        }

        /// <summary>
        /// 重新加载数据
        /// </summary>
        /// <returns>是否重新加载成功</returns>
        public static bool ReloadData()
        {
            if (string.IsNullOrEmpty(_configFilePath))
            {
                return false;
            }
            
            return LoadFromJsonFile(_configFilePath);
        }

        /// <summary>
        /// 获取数据统计信息
        /// </summary>
        /// <returns>统计信息字符串</returns>
        public static string GetDataStatistics()
        {
            if (!_isDataLoaded || _systemTypeConfig?.Types == null)
            {
                return "未加载数据";
            }
            
            return $"已加载 {_systemTypeConfig.Types.Count} 个系统类型";
        }

        /// <summary>
        /// 导出配置到JSON文件
        /// </summary>
        /// <param name="filePath">输出文件路径</param>
        /// <param name="systemTypes">要导出的系统类型列表</param>
        public static void ExportToJsonFile(string filePath, List<SystemTypeItem> systemTypes)
        {
            var config = new SystemTypeConfig
            {
                Types = systemTypes
            };
            
            string jsonContent = Newtonsoft.Json.JsonConvert.SerializeObject(config, Formatting.Indented);
            File.WriteAllText(filePath, jsonContent, new UTF8Encoding(false));
        }
    }
}
